<template>
  <div class="base-container" id="main">
    <div style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 29px;padding: 20px">
      重大研发专项计划需求征集表
    </div>
    <t-form labelAlign="top" ref="form" :data="formData" :rules="rules" class="step-form table-form"
            labelWidth="140px">
      <t-row>
        <t-col :span="2" class="title">基本信息</t-col>
        <t-col :span="10" style="display:block;padding: 0 !important; border: 0">
          <t-row>
            <t-col :span="2" class="sub-title text-center"><span class="require">*</span>研究方向</t-col>
            <t-col :span="10">
              <t-form-item name="researchDirection">
                <t-input clearable v-model="formData.researchDirection">
                </t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title text-center"><span class="require">*</span>研发需求
            </t-col>
            <t-col :span="10">
              <t-form-item  name="projectName">
                <t-input clearable v-model="formData.projectName">
                </t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title text-center"><span class="require">*</span>提出人（团队）</t-col>
            <t-col :span="10">
              <t-form-item  name="introducer">
                <t-input clearable v-model="formData.introducer">
                </t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title text-center"><span class="require">*</span>所在单位</t-col>
            <t-col :span="10">
              <t-form-item  name="deptName">
                <t-input clearable v-model="formData.deptName">
                </t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title text-center"><span class="require">*</span>联系电话</t-col>
            <t-col :span="10">
              <t-form-item  name="phone">
                <t-input clearable v-model="formData.phone">
                </t-input>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">相关附件</t-col>
        <t-col :span="10">
          <t-table size="small" row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{row, rowIndex}">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{row}">
              <file-upload v-model="row.fileIds" :moduleKey="row.moduleKey"
                           :fileList="row.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-col>
      </t-row>
    </t-form>

    <t-row style="margin-top: 20px;text-align: center">
      <t-col :span="12">
        <t-space :size="10">
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
              applyLoading ? '提交中...' : '暂存'
            }}
          </t-button>
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
              applyLoading ? '提交中...' : '提交'
            }}
          </t-button>
        </t-space>
      </t-col>
    </t-row>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "special-plan-apply",
  dicts: [],
  components: {
    FileUpload
  },
  data() {
    return {
      file_domain: VITE_FILE_DOMAIN,
      formData: {
        id: null,
        researchDirection: '',
        projectName: '',
        introducer: '',
        deptName: '',
        phone: '',
      },
      rules: {
        researchDirection: [
          {
            required: true,
            message: "研究方向不能为空",
          }
        ],
        projectName: [
          {
            required: true,
            message: "研发需求不能为空",
          }
        ],
        introducer: [
          {
            required: true,
            message: "提出人（团队）不能为空",
          }
        ],
        deptName: [
          {
            required: true,
            message: "所在单位不能为空",
          }
        ],
        phone: [
          {required: true, message: "联系电话不能为空"}
        ],
      },
      applyLoading: false,
      projectFileData: [
        {
          id: 1,
          c1: "需求征集表",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectXQZJB",
          require: true,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
    }
  },
  created() {
    if (this.$route.params.taskId) {
      this.$api.ggxq.specialPlan.get(this.$route.params.taskId).then(response => {
        if (!response.data) {
          return false;
        }
        this.formData = Object.assign({}, this.formData, response.data)
        getFiles(response.data.id).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }).catch(e => {
        this.$message.error(e.toString())
      })
    }
  },
  methods: {
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val=>{
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.$refs.form.validate({
          fields: ['researchDirection', 'projectName']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.ggxq.specialPlan.add({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.ggxq.specialPlan.update({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      } else {

        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            if (!this.formData.id) {
              this.$api.ggxq.specialPlan.add({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('提交成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.ggxq.specialPlan.update({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('提交成功');
                this.close();
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }

          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    },
    close() {
      this.$tab.closeOpenPage({path: "/ggxq/specialPlan/special-plan-index"});
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-table__empty {
  min-height: initial;
}
</style>
